﻿using System;
using System.Data;
using System.Collections.Generic;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using EKETEAM.FrameWork;
using EKETEAM.Data;
using EKETEAM.Tencent.WeChat;
using LitJson;

namespace eFrameWork.Plugins
{
    public partial class WeChatScanLogin : System.Web.UI.Page
    {
        public string UserArea = "Application";
        eUser user;
        string redirectUrl = "";
        public string fromURL = "";
        //开放平台申请 网站应用才可以扫码登录，公众号不支持。
        protected void Page_Load(object sender, EventArgs e)
        {
            fromURL = eParameters.QueryString("fromURL");
            string area = eParameters.QueryString("area");
            if (Request.QueryString["mode"] != null)
            {
                if (area.Length > 0 && fromURL.Length > 0)
                {
                    fromURL += (fromURL.IndexOf("?") == -1 ? "?" : "&") + "area=" + area;
                }
                return;
            }
          
            fromURL = eParameters.QueryString("state");
            redirectUrl = HttpUtility.UrlEncode(Request.Url.Path() + Request.Url.File());
            string code = Request["code"];
            if (string.IsNullOrEmpty(code))
            {
                OpenAccess();
            }
            if (fromURL.getQuery("area").Length > 0)
            {
                UserArea = fromURL.getQuery("area");
                fromURL = fromURL.removeQuery("area");
            }
            user = new eUser(UserArea);
            string _fromURL = HttpUtility.UrlDecode(fromURL);
            JsonData json = WeChatHelper.getOpenAccessToken(code);
            string accesstoken = json.GetValue("access_token");
            string openid = json.GetValue("openid");
            string unionid = json.GetValue("unionid");
            if (openid.Length == 0 && unionid.Length == 0)
            {
                if (_fromURL.ToLower().StartsWith("http"))
                {
                    JsonData jd = new JsonData();
                    jd.Add("success", "1");
                    jd.Add("errcode", "1");
                    jd.Add("message", "授权失败!");
                    string _base64 = Base64.Encode(jd.ToJson());
                    fromURL = HttpUtility.UrlDecode(fromURL);
                    fromURL = fromURL.addQuery("data", _base64);
                    Response.Redirect(fromURL, true);
                }
                else
                {
                    Response.Write("授权失败!");
                    Response.End();
                }
            }
            if (_fromURL.ToLower().StartsWith("http"))
            {
                string[] arr = _fromURL.Split("/".ToCharArray());
                string host = arr[2].ToLower();
                if (eBase.WeChatAccount.getValue("ReverseProxy").ToLower().IndexOf(host) > -1 || Request.Url.Host.ToLower() == host)
                {
                    json = WeChatHelper.getUserInfo(accesstoken, openid);
                    string _base64 = Base64.Encode(json.ToJson());
                    _fromURL = _fromURL.addQuery("data", _base64);
                    Response.Redirect(_fromURL, true);
                }
                eBase.End();
            }


            DataTable tb = eBase.UserInfoDB.getDataTable("select top 1 * from a_eke_sysUsers where (openid='" + openid + "'" + (unionid.Length > 0 ? " or unionid='" + unionid + "'" : "") + ") and delTag=0 order by addTime");
            if (tb.Rows.Count > 0)
            {
                


                if (tb.Rows[0]["Active"].ToString() == "False")
                {
                    Response.Write("登录失败,用户信息已停用!");
                    Response.End();
                }
                user = new eUser(UserArea);
                eFHelper.saveUserInfo(user, tb.Rows[0]); //保存用户登录信息
                eFHelper.UserLoginLog(user); //用户登录日志
                Response.Redirect(HttpUtility.UrlDecode(fromURL), true);
                Response.End();
            }
            else
            {
                //JsonData jd = WeChatHelper.getUserInfo(accesstoken, openid);//获取用户信息
                Response.Write("登录失败!");
                Response.End();
            }
        }
        private void OpenAccess()
        {
            //开放平台申请 网站应用才可以扫码登录，公众号不支持。
            if (!user.Logined)
            {
                //认证第一步：重定向跳转至认证网址
                string url = "https://open.weixin.qq.com/connect/qrconnect?appid=" + eBase.WeChatAccount.getValue("OpenAppID") + "&redirect_uri=" + redirectUrl + "&response_type=code&scope=snsapi_login&state=STATE#wechat_redirect";
                Response.Redirect(url);
            }
            else
            {
                //跳转到前端页面.aspx
                Response.Redirect(Request.Url.ToString());
            }
        }
    }
}